package com.bootdo.wx.api;

import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.wx.dao.MemberCouponDao;
import com.bootdo.wx.dao.OrderTeamDao;
import com.bootdo.wx.dao.OrderTeamUserDao;
import com.bootdo.wx.domain.*;
import com.bootdo.wx.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;

/**
 * Created by HP on 2019/5/29.
 */
@Controller
@RequestMapping("/api/order")
public class ApiOrderController {

    @Autowired
    private OrderOrderService orderOrderService;
    @Autowired
    private MemberCartService memberCartService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private GoodsProductService goodsProductService;
    @Autowired
    private MemberCouponDao memberCouponDao;
    @Autowired
    private GoodsSpikeService goodsSpikeService;
    @Autowired
    private GoodsNineService goodsNineService;
    @Autowired
    private GoodsBargainService goodsBargainService;
    @Autowired
    private GoodsGoodsService goodsGoodsService;
    @Autowired
    private OrderTeamDao orderTeamDao;
    @Autowired
    private OrderTeamUserDao orderTeamUserDao;

    /*
    * 购物车创建订单
    * cartList :  cartId
    * postType   0:自提(自提时，运费为0)，1：快递
    * payType: 0：微信支付，1：支付宝支付, 2：余额支付
    * */
    @RequestMapping("/addCartOrder")
    @ResponseBody
    public R addCartOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("cartList") || StringUtils.isBlank(paramMap.get("cartList").toString())
                    || !paramMap.containsKey("buyerMsg")
                    || !paramMap.containsKey("postFee") || StringUtils.isBlank(paramMap.get("postFee").toString())
                    || !paramMap.containsKey("addressId")
                    || !paramMap.containsKey("postType") || StringUtils.isBlank(paramMap.get("postType").toString())
                    || !paramMap.containsKey("payType") || StringUtils.isBlank(paramMap.get("payType").toString())
                    || !paramMap.containsKey("couponId")
                    ) {
                return R.error("参数错误");
            }
            List<String> errorList = new ArrayList<String>();  //错误订单集合
            List<String> cartList = (List<String>)paramMap.get("cartList"); //商品集合
            for (String cartId : cartList) {
                MemberCartDO cart = memberCartService.get(cartId);
                String goodsId = cart.getGoodsId();
                //判断是否可买
                String productId = cart.getProductId();
                GoodsProductDO product = goodsProductService.get(productId);
                int total = cart.getNum();
                Map<String,Object> canMap = new HashMap<String,Object>();
                canMap.put("xId",goodsId);
                canMap.put("type",0);
                canMap.put("productId",productId);
                canMap.put("num",total);
                canMap.put("userId",paramMap.get("userId"));
                R r = goodsGoodsService.isCanBye(canMap);
                if (Integer.valueOf(r.get("code").toString()) != 0) {
                    return r;
                }
            }
            String userId = paramMap.get("userId").toString();
            MemberUserDO user = memberUserService.get(userId);
            int disabled = user.getDisabled();
            if (disabled == 1) {
                return R.error(2,"该账号已经冻结，请联系平台管理员");
            }
            //判断优惠券是否可用
            String couponId = paramMap.get("couponId").toString();
            MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
            if (memberCouponDO != null) {
                int status = memberCouponDO.getStatus();
                if (status != 0) {
                    return R.error("该优惠券不能使用");
                }
            }
            return orderOrderService.addCartOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }

    /*
    * 商品详情创建订单（普通、拼团、会员专区）
    * type  0：普通商品，1:9.9商品，2：秒杀商品，4：拼团商品，5：会员专区商品 6 积分
    * id：type为0时传商品id，type为1时传秒杀id，type为2时传9.9专区id, type为4时传拼团id，type为5时传会员专区id
    * postType   0:自提，1：快递
    * payType: 0：微信支付，1：支付宝支付, 2：积分支付
    * */
    @RequestMapping("/addGoodsOrder")
    @ResponseBody
    public R addGoodsOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("id") || StringUtils.isBlank(paramMap.get("id").toString())
                    || !paramMap.containsKey("productId") || StringUtils.isBlank(paramMap.get("productId").toString())
                    || !paramMap.containsKey("total") || StringUtils.isBlank(paramMap.get("total").toString())
                    || !paramMap.containsKey("buyerMsg")
                    || !paramMap.containsKey("postFee") || StringUtils.isBlank(paramMap.get("postFee").toString())
                    || !paramMap.containsKey("addressId")
                    || !paramMap.containsKey("type") || StringUtils.isBlank(paramMap.get("type").toString())
                    || !paramMap.containsKey("postType") || StringUtils.isBlank(paramMap.get("postType").toString())
                    || !paramMap.containsKey("payType") || StringUtils.isBlank(paramMap.get("payType").toString())
                    || !paramMap.containsKey("couponId")
                    ) {
                return R.error("参数错误");
            }
            Integer type = Integer.valueOf(paramMap.get("type").toString());
            String productId = paramMap.get("productId").toString();
            String id = paramMap.get("id").toString();
            Integer total = Integer.valueOf(paramMap.get("total").toString());
            Map<String,Object> canMap = new HashMap<String,Object>();
            canMap.put("xId",id);
            canMap.put("type",type);
            canMap.put("productId",productId);
            canMap.put("num",total);
            canMap.put("userId",paramMap.get("userId"));
            R r = goodsGoodsService.isCanBye(canMap);
            if (Integer.valueOf(r.get("code").toString()) != 0) {
                return r;
            }

            String userId = paramMap.get("userId").toString();
            MemberUserDO user = memberUserService.get(userId);
            int disabled = user.getDisabled();
            if (disabled == 1) {
                return R.error(2,"该账号已经冻结，请联系平台管理员");
            }
            //判断优惠券是否可用
            String couponId = paramMap.get("couponId").toString();
            MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
            if (memberCouponDO != null) {
                int status = memberCouponDO.getStatus();
                if (status != 0) {
                    return R.error("该优惠券不能使用");
                }
            }
            return orderOrderService.addGoodsOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }

    /*
    * 去拼团，创建订单
    * type  0：普通商品，1:9.9商品，2：秒杀商品，4：拼团商品，5：会员专区商品
    * id：type为0时传商品id，type为1时传秒杀id，type为2时传9.9专区id, type为4时传拼团id，type为5时传会员专区id
    * postType   0:自提，1：快递
    * payType: 0：微信支付，1：支付宝支付, 2：余额支付
    * teamId: order_team表ID
    * */
    @RequestMapping("/addTeamGoodsOrder")
    @ResponseBody
    public R addTeamGoodsOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("id") || StringUtils.isBlank(paramMap.get("id").toString())
                    || !paramMap.containsKey("productId") || StringUtils.isBlank(paramMap.get("productId").toString())
                    || !paramMap.containsKey("total") || StringUtils.isBlank(paramMap.get("total").toString())
                    || !paramMap.containsKey("buyerMsg")
                    || !paramMap.containsKey("postFee") || StringUtils.isBlank(paramMap.get("postFee").toString())
                    || !paramMap.containsKey("addressId")
                    || !paramMap.containsKey("type") || StringUtils.isBlank(paramMap.get("type").toString())
                    || !paramMap.containsKey("postType") || StringUtils.isBlank(paramMap.get("postType").toString())
                    || !paramMap.containsKey("payType") || StringUtils.isBlank(paramMap.get("payType").toString())
                    || !paramMap.containsKey("teamId") || StringUtils.isBlank(paramMap.get("teamId").toString())
                    || !paramMap.containsKey("couponId")
                    ) {
                return R.error("参数错误");
            }
            Integer type = Integer.valueOf(paramMap.get("type").toString());
            String productId = paramMap.get("productId").toString();
            String teamId = paramMap.get("teamId").toString();
            String id = paramMap.get("id").toString();
            Integer total = Integer.valueOf(paramMap.get("total").toString());
            Map<String,Object> canMap = new HashMap<String,Object>();
            canMap.put("xId",id);
            canMap.put("type",type);
            canMap.put("productId",productId);
            canMap.put("num",total);
            canMap.put("userId",paramMap.get("userId"));
            R r = goodsGoodsService.isCanBye(canMap);
            if (Integer.valueOf(r.get("code").toString()) != 0) {
                return r;
            }

            String userId = paramMap.get("userId").toString();
            MemberUserDO user = memberUserService.get(userId);
            int disabled = user.getDisabled();
            if (disabled == 1) {
                return R.error(2,"该账号已经冻结，请联系平台管理员");
            }
            //判断优惠券是否可用
            String couponId = paramMap.get("couponId").toString();
            MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
            if (memberCouponDO != null) {
                int status = memberCouponDO.getStatus();
                if (status != 0) {
                    return R.error("该优惠券不能使用");
                }
            }
            //判断拼团订单是否过期
            OrderTeamDO orderTeamDO = orderTeamDao.get(teamId);
            canMap.clear();
            canMap.put("orderTeamId", teamId);
            canMap.put("isMain","1");
            String orderId = orderTeamUserDao.list(canMap).get(0).getOrderId();
            int status = orderOrderService.get(orderId).getStatus();
            Date updateAt = orderTeamDO.getUpdateAt();  //拼团结束时间
            Date now = new Date();
            if (status != 2 || updateAt.compareTo(now) == -1) {
                return R.error("此次拼团已结束");
            }
            //判断自己是否拼过团
            canMap.clear();
            canMap.put("teamId", teamId);
            canMap.put("userId",userId);
            List<Map<String,Object>> userList = orderTeamUserDao.panUser(canMap);
            if (userList.size() != 0) {
                return R.error("你已经拼过团了");
            }
            return orderOrderService.addGoodsOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }

    /*
    * 创建砍价订单
    * total 固定为 1
    * */
    @RequestMapping("/addBargainOrder")
    @ResponseBody
    public R addBargainOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("bargainId") || StringUtils.isBlank(paramMap.get("bargainId").toString())
                    || !paramMap.containsKey("productId") || StringUtils.isBlank(paramMap.get("productId").toString())
                    || !paramMap.containsKey("total") || StringUtils.isBlank(paramMap.get("total").toString())
                    || !paramMap.containsKey("buyerMsg")
                    || !paramMap.containsKey("postFee") || StringUtils.isBlank(paramMap.get("postFee").toString())
                    || !paramMap.containsKey("addressId") || StringUtils.isBlank(paramMap.get("addressId").toString())
                    || !paramMap.containsKey("couponId")
                    ) {
                return R.error("参数错误");
            }
            String productId = paramMap.get("productId").toString();
            String bargainId = paramMap.get("bargainId").toString();
            Integer total = Integer.valueOf(paramMap.get("total").toString());
            if (total != 1) {
                return R.error("该商品只能买一件");
            }
            GoodsProductDO product = goodsProductService.get(productId);
            int stock = product.getStock();  //库存
            if (stock < total) {
                return R.error("商品库存不足，请选择其他商品");
            }
            int bargainNum = goodsBargainService.get(bargainId).getStock();
            if (bargainNum < total) {
                return R.error("该专区商品已卖完，请选择其他商品");
            }

            String userId = paramMap.get("userId").toString();
            MemberUserDO user = memberUserService.get(userId);
            int disabled = user.getDisabled();
            if (disabled == 1) {
                return R.error(2,"该账号已经冻结，请联系平台管理员");
            }
            //判断优惠券是否可用
            String couponId = paramMap.get("couponId").toString();
            MemberCouponDO memberCouponDO = memberCouponDao.get(couponId);
            if (memberCouponDO != null) {
                int status = memberCouponDO.getStatus();
                if (status != 0) {
                    return R.error("该优惠券不能使用");
                }
            }
             return  orderOrderService.addBargainGoodsOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("请重新提交");

        }
    }


    /*
    * 查看个人订单
    * type 1:待支付， 2：代发货，3：待收货（包括自提），4：待评价，5：问题订单，0：全部，7：拼团中
    * */
    @ResponseBody
    @RequestMapping("/getOrderList")
    public R getOrderList(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("type") || StringUtils.isBlank(paramMap.get("type").toString())) {
                return R.error("参数错误");
            }
            PageInfo<Map<String,Object>> list = orderOrderService.getOrderListByStatus(paramMap);
            return R.ok().put("data", list);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败");
        }

    }

    /*
    * 取消/收货 订单
    * type ，8：订单取消，7：收货
    * */
    @ResponseBody
    @RequestMapping("/setStatusOrder")
    public R setStatusOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("type") || StringUtils.isBlank(paramMap.get("type").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())
                    ) {
                return R.error("参数错误");
            }
            if(orderOrderService.setStatusOrder(paramMap) == 0) {
                return R.ok();
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    /*
    * 评价订单
    * comentList   start:星级，content:评价内容, detailId：分订单id，imgurls
    * */
    @ResponseBody
    @RequestMapping("/setComent")
    public R setComent(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("comentList") || StringUtils.isBlank(paramMap.get("comentList").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())
                    ) {
                return R.error("参数错误");
            }
            Map<String,Object> map = new HashMap<String,Object>();
            map.put("userId",paramMap.get("userId"));
            map.put("id",paramMap.get("orderId"));
            List<OrderOrderDO> orderList = orderOrderService.list(map);
            if (orderList.size() == 0) {
                return R.error("订单异常");
            }
            OrderOrderDO orderOrderDO = orderList.get(0);
            if (orderOrderDO.getComent() == 1) {
                return R.error("订单已评价");
            }
            if (orderOrderDO.getStatus() != 7) {
                return R.error("该订单暂不能评价");
            }

            int a = orderOrderService.setComent(paramMap);
            if(a == 0) {
                return R.ok();
            } else if (a == 1) {
                return R.error("评价内容不能为空");
            }
            return R.error();
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    /*
    * 订单详情(普通、秒杀、会员专区、9.9)
    * */
    @ResponseBody
    @RequestMapping("/getOrderById")
    public R getOrderById(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())
                    ) {
                return R.error("参数错误");
            }
            Map<String,Object> map = orderOrderService.getOrderById(paramMap);
            return R.ok().put("data", map);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    /*
    * 订单详情(拼团订单)
    * */
    @ResponseBody
    @RequestMapping("/getPOrderById")
    public R getPOrderById(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())
                    ) {
                return R.error("参数错误");
            }
            Map<String,Object> map = orderOrderService.getPOrderById(paramMap);
            return R.ok().put("data",map);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    /*
    * 订单详情(砍价)
    * */
    @ResponseBody
    @RequestMapping("/getKOrderById")
    public R getKOrderById(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())
                    ) {
                return R.error("参数错误");
            }
            Map<String,Object> map = orderOrderService.getKOrderById(paramMap);
            return R.ok().put("data",map);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("操作失败");
        }
    }

    /*
    * 申请退货
    * */
    @ResponseBody
    @RequestMapping("/backGood")
    public R backGood(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("id") || StringUtils.isBlank(paramMap.get("id").toString())
                    || !paramMap.containsKey("expressName")
                    || !paramMap.containsKey("expressCode")
                    || !paramMap.containsKey("reason") || StringUtils.isBlank(paramMap.get("reason").toString())
                    ) {
                return R.error("参数错误");
            }
            //paramMap.put("status", "4");   //待收货
            List<OrderOrderDO> orderList = orderOrderService.list(paramMap);
            if (orderList.size() == 0) {
                return R.error("订单错误");
            }
            int status = orderList.get(0).getStatus();
            if (status !=4 && status != 11) {
                return R.error("该订单不能退货");
            }
            if (orderOrderService.backGood(paramMap) == 1) {
                return R.ok();
            } else {
                return R.error();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("失败");
        }
    }

    /*
    * 删除订单
    * */
    @ResponseBody
    @RequestMapping("/removeOrder")
    public R removeOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("orderIdList") || StringUtils.isBlank(paramMap.get("orderIdList").toString())
                    ) {
                return R.error("参数错误");
            }
            return orderOrderService.removeOrder(paramMap);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("失败");
        }
    }
    
    /**
     * 
     * @author long
     * 2020年7月18日下午2:06:08
     * 方法释义:获取运费
     * 参数: type 0 购物车获取运费  1单个产品获取运费
     *
     */
    @ResponseBody
    @RequestMapping("/getPostFee")
    public R getPostFee(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("type") || StringUtils.isBlank(paramMap.get("type").toString())
                    ) {
                return R.error("参数错误");
            }
            BigDecimal postFee = null;
            if(paramMap.get("type").toString().equals("0")){
            	 List<String> cartList = (List<String>)paramMap.get("cartList");
            	 postFee = orderOrderService.getPostFees(paramMap,cartList);
            }else{
            	  postFee = orderOrderService.getPostFees(paramMap,paramMap.get("goodsId").toString(),paramMap.get("productId").toString());
            }
            
            return R.ok().put("data", postFee);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败");
        }

    }


    /*
    * 得到别人分享的拼团订单
    * */
    @ResponseBody
    @RequestMapping("/getTeamOrder")
    public R getTeamOrder(@RequestBody Map<String,Object> paramMap) {
        try{
            if (!paramMap.containsKey("userId") || StringUtils.isBlank(paramMap.get("userId").toString())
                    || !paramMap.containsKey("orderId") || StringUtils.isBlank(paramMap.get("orderId").toString())) {
                return R.error("参数错误");
            }
            Map<String,Object> map = orderOrderService.getTeamOrder(paramMap);
            return R.ok().put("data", map);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("查询失败");
        }

    }




}
